/**
 * 阀门历史记录
 */
'use strict';


const conn = require('../../libs/DB/Conn');
const _ = require("underscore");
const {timeComponent,chartDataProcessing} = require("../../libs/Utils")
const moment = require("moment/moment");
const columnNameObj = require("./deviceChartConfig").chart.coolingMachine;
const deviceType = require("./deviceChartConfig").type.refrigeratingMachine;

module.exports = async function (params) {
    try {
        let timeInterval = timeComponent(params.startTime,params.endTime,params.type);
        let sql = `SELECT
            dd.device_no AS deviceNo,
            DATE_FORMAT(dd.data_time,"%Y-%m-%d %H:%i:%s") AS dataTime,
            ${timeInterval.queryGroupTime} 
            df.device_name AS deviceName,
            dd.runtime,
            dd.status,
            dd.fault_type AS faultType,
            dd.chilled_water_outlet_temperature AS chilledWaterOutletTemperature,
            dd.chilled_water_return_temperature AS chilledWaterReturnTemperature,
            dd.cooling_water_outlet_temperature AS coolingWaterOutletTemperature,
            dd.cooling_water_return_temperature AS coolingWaterReturnTemperature,
            dd.preset_current_percentage AS presetCurrentPercentage,
            dd.actual_current_percentage AS actualCurrentPercentage,
            rf.range_name AS rangeName
        FROM
        data_refrigerating_machine_${params.userDomainId} dd
        INNER JOIN device_file df ON df.device_no = dd.device_no
        AND df.delete_sign = 1 AND df.device_type = ${deviceType} 
        AND df.range_id IN (?)
        INNER JOIN range_file rf ON df.range_id = rf.range_id AND rf.delete_sign = 1 
        WHERE 1 = 1 ${timeInterval.startTime && timeInterval.endTime ? ` AND (dd.data_time > "${timeInterval.startTime}" AND dd.data_time <= "${timeInterval.endTime}")` : `` } 
        ORDER BY dd.data_time DESC`;
        let heatDataList = await conn(sql,[params.rangeIds]);
        let heatDataGroup = _.groupBy(heatDataList,"deviceNo");
        let dataList = [];
        for(const deviceNo in heatDataGroup){
            let deviceDataList = heatDataGroup[deviceNo];
            let deviceObj = {
                deviceName:deviceDataList[0].deviceName,
                rangeName:deviceDataList[0].rangeName,
                deviceNo:deviceNo,
                runtime:"00:00:00",
                status:deviceDataList[0].status,
                faultType:deviceDataList[0].faultType,
                chilledWaterOutletTemperature:deviceDataList[0].chilledWaterOutletTemperature,
                chilledWaterReturnTemperature:deviceDataList[0].chilledWaterReturnTemperature,
                coolingWaterOutletTemperature:deviceDataList[0].coolingWaterOutletTemperature,
                coolingWaterReturnTemperature:deviceDataList[0].coolingWaterReturnTemperature,
                actualCurrentPercentage:deviceDataList[0].actualCurrentPercentage,
                presetCurrentPercentage:deviceDataList[0].presetCurrentPercentage,
                dataList:[],
            }
            deviceDataList.forEach(function (data){
                let runtime = moment.duration(deviceDataList[0].runtime).add(moment.duration(data.runtime));
                deviceObj.runtime =  moment.utc(runtime.asMilliseconds()).format('HH:mm:ss');
            })
            if(params.type === "hour"){
                deviceObj.dataList = deviceDataList
            }else {
                let timeGroup = _.groupBy(deviceDataList,"groupTime");
                for(const time in timeGroup){
                    let timeGroupList = timeGroup[time];
                    let deviceDataObj = {
                        dataTime:time,
                        dataCreateTime:timeGroupList[timeGroupList.length - 1].dataTime,
                        runtime:"00:00:00",
                        status:timeGroupList[0].status,
                        faultType:timeGroupList[0].faultType,
                        chilledWaterOutletTemperature:timeGroupList[0].chilledWaterOutletTemperature,
                        chilledWaterReturnTemperature:timeGroupList[0].chilledWaterReturnTemperature,
                        coolingWaterOutletTemperature:timeGroupList[0].coolingWaterOutletTemperature,
                        coolingWaterReturnTemperature:timeGroupList[0].coolingWaterReturnTemperature,
                        actualCurrentPercentage:timeGroupList[0].actualCurrentPercentage,
                        presetCurrentPercentage:timeGroupList[0].presetCurrentPercentage,
                    }
                    deviceDataList.forEach(function (data){
                        let runtime = moment.duration(deviceDataObj.runtime).add(moment.duration(data.runtime));
                        deviceDataObj.runtime =  moment.utc(runtime.asMilliseconds()).format('HH:mm:ss');
                    })
                    deviceObj.dataList.push(deviceDataObj);
                }
            }
            deviceObj.chart = chartDataProcessing(deviceObj.dataList,columnNameObj);
            dataList.push(deviceObj);
        }
        return { success: true,dataList:dataList};
    }catch (e){
        return { success: false,dataList:[],message:e.code === "ER_NO_SUCH_TABLE" ? "当前账号无此类设备" : e.sqlMessage};
    }
};